package servlet;

import Dao.JdbcTools;
import model.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/updateok")
public class Updaeok extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //动态生成表单
        //1.设置
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //2.收参
        String id =req.getParameter("id");
        String name =req.getParameter("name");
        String sex =req.getParameter("sex");
        String age =req.getParameter("age");
        String major =req.getParameter("major");

        try {
            int i = JdbcTools.update1("update student set name=?,sex=?,age=?,major=? where id=?",
                    name,sex,age,major,id);
            System.out.println("i = " + i);
            //更新之后查询数据库重新渲染页面
            //获取数据库中展示数据
            List<Student> stulist = null;
            try {
                stulist = JdbcTools.queryBeanList("select * from student", Student.class);
                //数据展示 servlet
//                req.setAttribute("stulist", stulist);
//                req.getRequestDispatcher("showlist").forward(req, resp);
                req.setAttribute("stulist", stulist);
                req.getRequestDispatcher("showlist1.jsp").forward(req, resp);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
